package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.itheima.cart.pojo.ShoppingCart;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.StatusConstant;
import com.itheima.context.BaseContext;
import com.itheima.dto.OrdersStatisticsDto;
import com.itheima.exception.BaseException;
import com.itheima.exception.OrderBusinessException;
import com.itheima.mapper.AddressBookMapper;
import com.itheima.dto.OrdersPageQueryDTO;
import com.itheima.dto.OrdersPaymentDTO;
import com.itheima.dto.OrdersSubmitDTO;
import com.itheima.feign.ShoppingCartClient;
import com.itheima.mapper.OrderDetailMapper;
import com.itheima.mapper.OrderMapper;
import com.itheima.pojo.AddressBook;
import com.itheima.pojo.OrderDetail;
import com.itheima.pojo.Orders;
import com.itheima.service.OrderService;
import com.itheima.vo.BusinessDataVO;
import com.itheima.vo.TurnoverReportVO;
import com.itheima.vo.*;
import com.itheima.websocket.WebSocketServer;
import com.itheima.result.PageBean;
import com.itheima.result.Result;
import com.itheima.vo.SalesTop10ReportVO;
import com.itheima.utils.BaiduApiUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;

//    @Autowired
//    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private ShoppingCartClient shoppingCartClient;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WebSocketServer webSocketServer;


    @Override
    public PageBean page(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrderVO> orders = orderMapper.pageSelect(ordersPageQueryDTO);
        return new PageBean(orders.getTotal(), orders.getResult());
    }

    @Autowired
    private BaiduApiUtils baiduApiUtils;
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook1 = addressBookMapper.getById(addressBookId);
        String ad=addressBook1.getProvinceName()+addressBook1.getCityName()+addressBook1.getDistrictName()+addressBook1.getDetail();
        Double distance = baiduApiUtils.calculateDistance(ad);
        if (distance>5000){
            throw  new BaseException("距离太远");
        }

        Long userId = BaseContext.getCurrentId();
        //添加订单表1
        AddressBook book = AddressBook.builder().userId(userId)
                .isDefault(1).build();
        AddressBook defaultAddress = addressBookMapper.getDefaultAddress(book);

        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setUserId(BaseContext.getCurrentId());

        String address = defaultAddress.getProvinceName() + defaultAddress.getCityName() + defaultAddress.getDistrictName() + defaultAddress.getDetail();
        orders.setAddress(address);

        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(StatusConstant.ENABLE);

        orders.setNumber(System.currentTimeMillis() + "");

        orders.setPayStatus(StatusConstant.DISABLE);

        orders.setPhone(defaultAddress.getPhone());
        orders.setConsignee(defaultAddress.getConsignee());

        orderMapper.add(orders);//主键自增返回
        //添加订单详细表，将购物车的信息添加到订单详细表

//        List<ShoppingCart> carts = shoppingCartMapper.getByDishIdOrSetmealIdWithUserId(ShoppingCart.builder().userId(userId).build());
        Result<List<ShoppingCart>> result = shoppingCartClient.getByDishIdOrSetmealIdWithUserId(ShoppingCart.builder().userId(userId).build());
        List<ShoppingCart> carts = result.getData();

        List<OrderDetail> orderDetails = carts.stream().map(cart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            return orderDetail;
        }).collect(Collectors.toList());
        //批量添加
        orderDetailMapper.insert(orderDetails);
        //完了之后要清空购物车
//        shoppingCartMapper.clean(userId);
        shoppingCartClient.clean(userId);

        return new OrderSubmitVO(orders.getId(), orders.getNumber(), orders.getAmount(), orders.getOrderTime());
    }
    /**
     * 订单支付
     * @param ordersPaymentDTO
     * @return
     */

    @Override
    public LocalDateTime getByNumber(OrdersPaymentDTO ordersPaymentDTO) {
        Orders orders = Orders.builder()
                .number(ordersPaymentDTO.getOrderNumber())
                .checkoutTime(LocalDateTime.now())
                .payMethod(ordersPaymentDTO.getPayMethod())
                .status(2)
                .payStatus(1)
                .estimatedDeliveryTime(LocalDateTime.now().plusMinutes(60)).build();
        orderMapper.updateById(orders);
        Map map = new HashMap();
        map.put("type", 1);//通知类型 1来单提醒 2客户催单
        map.put("orderId", orders.getId());//订单id
        map.put("content","订单号:" + ordersPaymentDTO.getOrderNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

        return orders.getEstimatedDeliveryTime();
    }

    @Override
    public PageBean pageHistoryOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Orders orders = new Orders();
        orders.setUserId(BaseContext.getCurrentId());
        BeanUtils.copyProperties(ordersPageQueryDTO, orders);
        Page<OrderVO> page = orderMapper.pageSelectHistoryOrder(orders);
        log.info("page为{}", page);
        log.info("=============={}", page.getResult());
        return PageBean.builder().total(page.getTotal()).records(page.getResult()).build();
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO findById(Long id) {
        Orders orders = Orders.builder().id(id).build();
        OrderVO order = orderMapper.findById(orders);
        return order;
    }

    /**
     * 取消订单
     *
     * @param id
     * @return
     */
    @Override
    public void cancelOrder(Long id) {
        Orders orders = Orders.builder().id(id).userId(BaseContext.getCurrentId()).build();
        OrderVO order = orderMapper.findById(orders);
        if (order == null) {
            return;
        }
        //仅待付款，待接单可以直接取消
        if (order.getStatus() == 1) {
            //可以取消订单
            order.setStatus(6);
            order.setCancelTime(LocalDateTime.now());

        }
        if (order.getStatus() == 2 && order.getPayStatus() == 1) {
            //待接单,进行退款
            order.setStatus(7);
            order.setPayStatus(2);
            order.setCancelTime(LocalDateTime.now());
        }
        order.setCancelReason("用户取消");
        orderMapper.updateOrderById(order);
    }

    /**
     * 再来一单
     *
     * @param id
     * @return
     */
    @Override
    public void addAgain(Long id) {
        OrderVO orderVO = orderMapper.findById(Orders.builder().id(id).userId(BaseContext.getCurrentId()).build());
        List<OrderDetail> orderDetails = orderVO.getOrderDetailList();
        ShoppingCart shoppingCart = new ShoppingCart();
        for (OrderDetail orderDetail : orderDetails) {
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
//            shoppingCartMapper.add(shoppingCart);
            shoppingCartClient.add(shoppingCart);

        }
    }

    /**
     * 后端接单
     *
     * @param orders
     * @return
     */
    @Override
    public void confirmOrder(Orders orders) {
        orders.setStatus(3);
        orderMapper.alterById(orders);
    }

    /**
     * 派送订单
     *
     * @param id
     * @return
     */
    @Override
    public void deliveryById(Long id) {
        Orders build = Orders.builder().id(id).status(4).build();
        orderMapper.alterById(build);
    }

    @Override
    public void reject(Orders orders) {
        orders.setStatus(7);
        orders.setPayStatus(2);
        orderMapper.alterById(orders);
    }

    /**
     * 取消订单
     *
     * @param orders
     * @return
     */
    @Override
    public void cancel(Orders orders) {
        OrderVO orderVO = orderMapper.findById(orders);
        if (orderVO.getStatus() != 1) {
            orders.setStatus(7);
            orders.setPayStatus(2);
        }
        orders.setStatus(6);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.alterById(orders);

    }

    /**
     * 完成订单
     *
     * @param id
     * @return
     */
    @Override
    public void complete(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(5)
                .deliveryTime(LocalDateTime.now()).build();
        orderMapper.alterById(orders);
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO getCount() {
        List<Map> maps = orderMapper.getcount();
        OrderStatisticsVO vo = new OrderStatisticsVO();
        for (Map map : maps) {
            if (map.get("status").equals(2)) {
                vo.setToBeConfirmed(Integer.parseInt(String.valueOf(map.get("count"))));
            }
            if (map.get("status").equals(3)) {
                vo.setConfirmed(Integer.parseInt(String.valueOf(map.get("count"))));
            }
            if (map.get("status").equals(4)) {
                vo.setDeliveryInProgress(Integer.parseInt(String.valueOf(map.get("count"))));
            }
        }
        log.info("maps为{}", maps);
        log.info("{}===", vo);
        return vo;
    }

    /**
     * 订单统计
     *
     * @param statisticsDto
     * @return
     */
    @Override
    public OrderReportVO orderStatistics(OrdersStatisticsDto statisticsDto) {
        OrderReportVO vo = orderMapper.orderStatistics(statisticsDto);
        log.info("订单统计：{}",vo);
        return vo;

    }
    /**
     * 查询销量排名top10接口
     * @param dto
     * @return
     */
    @Override
    public SalesTop10ReportVO top(OrdersStatisticsDto dto) {
        SalesTop10ReportVO vo= orderDetailMapper.top(dto);
        return vo;
    }
    /**
     * * 用户催单
     * * @param id
     * */
    @Override
    public void reminder(Long id) {
        //查询订单是否存在
        Orders orders=orderMapper.getById(id);
        if (orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //基于websocket实现催单
        Map map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号："+orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    @Override
    public TurnoverReportVO turnoverStatistics(OrdersStatisticsDto statisticsDto) {
        TurnoverReportVO vo = orderMapper.turnoverStatistics(statisticsDto);
        return vo;
    }

    @Override
    public BusinessDataVO getBusinessData(LocalDateTime begin, LocalDateTime end) {
        return orderMapper.getBusinessData(begin,end);
    }

    @Override
    public List<BusinessDataVO> getData(LocalDate begin, LocalDate end) {
        return orderMapper.getData(begin,end);
    }

    @Override
    public OrderOverViewVO overviewOrders() {
        return orderMapper.overviewOrders();
    }

    @Override
    public BusinessDataVO businessData() {

        return orderMapper.businessData();
    }
}